﻿package {
	
	import flash.events.Event;
	import flash.display.MovieClip;
	import flash.net.*;
	import flash.utils.ByteArray;
	
	public class FileLoader {
	
		private var fr:FileReference;
		private var elements:Array;
		private var elementTypes:Array;
		private var editor:Editor;
	
		public function FileLoader(ed:Editor, el:Array, et:Array) {
			elements = el;
			elementTypes = et;
			editor = ed;
		}
		
		public function loadFile():void {
			clearElements();
			fr = new FileReference();
			fr.browse(new Array(new FileFilter("XML", "*.xml")));
			fr.addEventListener(Event.SELECT, beginLoad);
		}
		
		private function clearElements() {
			for (var i:int = 0; i < elements.length; i++) {
				if (elements[i] is TextBox) {
					if(editor.contains(TextBox(elements[i]).getTextField())) editor.removeChild(TextBox(elements[i]).getTextField());
				} 
				if (elements[i] is ImageObject) {
					ImageObject(elements[i]).remove();
				}
			}
			elements = new Array();
			elementTypes = new Array();
		}
		
		private function beginLoad(e:Event) {
			fr.load();
			fr.addEventListener(Event.COMPLETE, addElements);
		}
		
		private function addElements(e:Event) {
			var data:ByteArray = fr.data;
			var xml:String = String(XML(data.readUTFBytes(data.bytesAvailable)));
			
			var regex:RegExp = new RegExp("Title=\"(.+)\"", "m");
			var str:String = xml.match(regex)[0];
			var title:String = (str.slice(7, -18));
			editor.pageProperties.title.text = title;
			var color:String = (str.slice(-9, -1));
			editor.pageProperties.setColor(parseInt(color));
			
			regex = new RegExp("<(.+)</(.+)>", "mg");
			var objects:Array = xml.match(regex);
			for (var i:int = 0; i < objects.length; i++) 
			{
				switch (String(objects[i]).substr(1, 4)) {
					case "Text":
						var textBox:TextBox = new TextBox(editor);
						textBox.fromXML(objects[i]);
						elements.push(textBox);
						elementTypes.push("textbox");
						editor.addChild(textBox.getTextField());
						break;
					case "Imag":
						var image:ImageObject = new ImageObject(editor);
						image.fromXML(objects[i]);
						elements.push(image);
						elementTypes.push("image");
						break;
				}
			}
		}
		
	}
}